package com.framework.bdf4j.job.controller;

import java.util.Arrays;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.framework.bdf4j.annotations.SysLog;
import com.framework.bdf4j.comm.persist.PageDomain;
import com.framework.bdf4j.comm.util.R;
import com.framework.bdf4j.comm.util.StringUtils;
import com.framework.bdf4j.job.entity.SysJob;
import com.framework.bdf4j.job.entity.SysJobLog;
import com.framework.bdf4j.job.service.SysJobLogService;
import com.framework.bdf4j.job.service.SysJobService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;

/**
 * 定时任务执行日志表
 */
@Controller
@AllArgsConstructor
@RequestMapping("/admin/joblog")
@Api(value = "joblog", tags = "定时任务日志")
public class SysJobLogController {
    private final SysJobService sysJobService;
    private final SysJobLogService sysJobLogService;

    @GetMapping("/index")
    public String goJobLog(@RequestParam(value = "jobId", required = false) Integer jobId, ModelMap mmap) {
        if (StringUtils.isNotNull(jobId)) {
            SysJob job = sysJobService.getById(jobId);
            mmap.put("job", job);
        }
        return "monitor/job/jobLogList";
    }

    /**
     * 分页查询
     *
     * @param page
     *            分页对象
     * @param sysJobLog
     *            定时任务执行日志表
     * @return
     */
    @GetMapping("/page")
    @ResponseBody
    @ApiOperation(value = "分页定时任务日志查询")
    public R getSysJobLogPage(Page page, PageDomain domain, SysJobLog sysJobLog) {
        OrderItem orderitem = StringUtils.getOrderItem(domain);
        if (orderitem != null) {
            page.addOrder(orderitem);
        }
        return R.ok(sysJobLogService.getJobLogPage(page, sysJobLog));
    }

    /**
     * 删除日志
     *
     * @param id
     *            ID
     * @return success/false
     */
    @ResponseBody
    @DeleteMapping("/{ids}")
    @SysLog("删除调度日志")
    public R removeById(@PathVariable String ids) {
        String[] logIds = ids.split(",");
        return R.ok(sysJobLogService.removeByIds(Arrays.asList(logIds)));
    }

    @ResponseBody
    @PostMapping("/clean")
    @SysLog("清空调度日志")
    public R clean() {
        return R.ok(sysJobLogService.remove(Wrappers.emptyWrapper()));
    }
}
